﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using Operation;
using pinduoduo.Util;
using Sunny.UI;
using Tk.Soc.Share.Common.Helpers;
using Util;

namespace pinduoduo.From
{
    public partial class AutoPayFrom : UIForm
    {

        private ChromiumWebBrowser AccountChromeBrowser;

        private RequestContext AccountContext;

        public string ZhiFuPassword { get; set; }

        private int type;

        private ChromeDriverService service;

        IWebDriver driver;

        private string payUrl;
        private string password;
        private bool isClose;

        public AutoPayFrom(string payUrl, string password)
        {
            this.payUrl = payUrl;
            this.password = password;
            InitializeComponent();
            InitializeAccountChromium();
         
        }

        private void AutoPayFrom_Load(object sender, EventArgs e)
        {
             
        }

        public async void AutoPay(bool isClose = false, int timeout = 5000)
        {
            this.panel1.Width = 460;
            this.panel1.Height = 658;
            this.Text = "支付";
            AccountChromeBrowser.Load(payUrl);
            this.Width = 466;
            this.Height = 698;

            Browser.Delay(1000);

            string js = "getElementsByText('确认付款','button')[0]";
            while (true)
            {
                int delay = 0;
                string temp = Browser.JS_CEFBrowser(js + "!=null", AccountChromeBrowser);
                if (!string.IsNullOrEmpty(temp) && temp == "True")
                {
                    Browser.MouseLeftByHtmlElement("getElementsByText('确认付款','button')[0]", AccountChromeBrowser, false);
                    Browser.MouseLeftByHtmlElement("document.getElementById('pwd_unencrypt')", AccountChromeBrowser, true);
                    Browser.Delay(300);
                    SendKeys.SendWait(password);
                    Browser.Delay(1000);
                    
                    if (AccountChromeBrowser.GetBrowser().MainFrame.Url.Contains("https://mclient.alipay.com/h5/cashierPay.htm?awid="))
                    {
                        delay = 0;
                        while (true)
                        {
                            string PageSource = await AccountChromeBrowser.GetBrowser().MainFrame.GetSourceAsync();
                            if (PageSource.Contains("短信校验码") && PageSource.Contains("收到的短信校验码"))
                            {
                                ShowErrorNotifier("任务失败");
                                break;
                            }

                            string script = @"(function() { return  document.getElementsByClassName('J-success')[0].offsetParent;})()";

                            JavascriptResponse javascriptResponse = await AccountChromeBrowser.EvaluateScriptAsync(script);
                            if (javascriptResponse.Result!=null&&!string.IsNullOrWhiteSpace(javascriptResponse.Result.ToString())) 
                            {
                                ShowSuccessNotifier("任务成功");

                                if (isClose)
                                {
                                    this.DialogResult = DialogResult.OK;
                                    this.Close();
                                }

                                return;
                            }
                           
                            await Task.Delay(500);
                            delay += 500;
                            if (delay > timeout * 1000)
                            {
                                break;
                            }
                        }

                        ShowErrorNotifier("任务失败");
                    }
                    else
                    {
                        ShowErrorNotifier("任务失败");
                    }
                    break;
                }

                await Task.Delay(500);
                delay += 500;
                if (delay > timeout * 1000)
                {
                    break;
                }
            }
        
        

            

           
            //Browser.MouseLeftByHtmlElement(ii.OuterHTML, this.chromeBrowser);

            //browser.FindElement(".text", 1).Click();
            //wait.UntilElementExist("#input_email");
            //browser.FindElement("#pwd_unencrypt").SendKeys("248789");
            //browser.FindElement(".-confirm").ToggleDisabled();

            //start process.
            //attach by friendly.

          
            //Auto.Ctrl_V("248789");
            //开始回复-复制粘贴
            //点击输入窗口


            //回车
            //Auto.Key_Enter();



            //service = ChromeDriverService.CreateDefaultService();
            //service.LogPath = AppDomain.CurrentDomain.BaseDirectory + "drive";
            //IWebDriver driver = await GetDriver(service);
         
            //if (driver == null)
            //{
            //    ShowErrorNotifier("自动支付驱动异常，请重试或重启软件!");
            //    return;
            //}
            //try
            //{

            //    if (true) 
            //    {
            //        driver.Navigate().GoToUrl(payUrl);
                    
            //        var shuru = By.XPath("//*[@id=\"kw\"]");
            //        driver.FindElement(shuru).Click();
            //        driver.FindElement(shuru).SendKeys("测试");
            //        ShowSuccessNotifier("任务成功");
            //        Thread.Sleep(1500);
            //        this.DialogResult = DialogResult.OK;
            //        this.Close();
            //        return;
            //    }
          
            //    var zhifuButton = By.XPath("//*[@id=\"cashierPreConfirm\"]/div[2]/button");
            //    driver.FindElement(zhifuButton).Click();
            //    var payInput = By.XPath("//*[@id=\"pwd_unencrypt\"]");
            //    driver.SwitchTo().DefaultContent();
            //    driver.FindElement(payInput).SendKeys(password);
            //    Thread.Sleep(2000);

            //    string nextUrl = driver.Url;
            //    if (nextUrl.Contains("https://mclient.alipay.com/h5/cashierPay.htm?awid="))
            //    {
            //        int delay = 0;
            //        while (true)
            //        {
            //            if (driver.PageSource.Contains("短信校验码") && driver.PageSource.Contains("收到的短信校验码"))
            //            {
            //                ShowErrorNotifier("任务失败");
            //                break;
            //            }
            //            var successEl = driver.FindElement(By.ClassName("J-success"));

            //            if (successEl != null && successEl.Displayed)
            //            {
            //                ShowSuccessNotifier("任务成功");

            //                if (isClose)
            //                {
            //                    this.DialogResult = DialogResult.OK;
            //                    this.Close();
            //                }

            //                return;
            //            }
            //            await Task.Delay(500);
            //            delay += 500;
            //            if (delay > timeout * 1000)
            //            {
            //                break;
            //            }
            //        }

            //        ShowErrorNotifier("任务失败");
            //    }
            //    else
            //    {
            //        ShowErrorNotifier("任务失败");
            //    }
            //}
            //catch (Exception e)
            //{
            //    LogHelper.Logger.Error("自动支付异常：", e);
            //    ShowErrorNotifier("任务失败");
            //}
            //finally
            //{
            //    await Task.Run(() =>
            //    {
            //        driver?.Close();
            //        driver?.Quit();
            //        driver?.Dispose();
            //    });

            //}
        }

        public async Task<IWebDriver> GetDriver(ChromeDriverService chromeDriverService = null)
        {
            IWebDriver driver = null;
            await Task.Run(() =>
            {
                try
                {
                    if (chromeDriverService == null)
                    {
                        chromeDriverService = service;
                    }
                    ChromeOptions options = new ChromeOptions();
                    options.DebuggerAddress = "127.0.0.1:22222";
                    chromeDriverService.HideCommandPromptWindow = true;
                    driver = new ChromeDriver(chromeDriverService, options, TimeSpan.FromSeconds(5));
                }
                catch (Exception e)
                {
                    driver?.Close();
                    driver?.Quit();
                    driver?.Dispose();
                }
            });
            return driver;
        }

        //初始化浏览器并启动
        public void InitializeAccountChromium()
        {

            AccountContext = new RequestContext(new RequestContextSettings()
            {
                CachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\global1\\",
                PersistSessionCookies = true,
                PersistUserPreferences = true
            });

            AccountChromeBrowser = new ChromiumWebBrowser(this.payUrl, AccountContext);
            BrowserSettings browserSettings = new BrowserSettings();
            browserSettings.ApplicationCache = CefState.Enabled;

            AccountChromeBrowser.BrowserSettings = browserSettings;

            AccountChromeBrowser.KeyboardHandler = new CEFKeyBoardHander();


            this.panel1.Controls.Add(AccountChromeBrowser);


            AccountChromeBrowser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;

            AccountChromeBrowser.Dock = DockStyle.Fill;
        }

        private void OnIsBrowserInitializedChanged(object sender, EventArgs args)
        {
            SetCookie(CefUtils.GetAccountContext());
        }

        private string pddurl = "http://yangkeduo.com/";

        public async void SetCookie(RequestContext AccountContext)
        {
            List<CefSharp.Cookie> cookies = await AccountContext.GetCookieManager(null).VisitUrlCookiesAsync(pddurl, true);

            foreach (var item in cookies)
            {
                await AccountChromeBrowser.GetCookieManager().SetCookieAsync(pddurl, item);
            }
        }

        private void AutoPayFrom_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void AutoPayFrom_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void AutoPayFrom_Shown(object sender, EventArgs e)
        {
            AutoPay();
        }
    }
}
